use actix_multipart::Multipart;
use actix_web::{web, HttpResponse, Responder};
use futures_util::StreamExt;
use serde::Deserialize;
use std::io::Write;

pub fn set_routes(cfg: &mut web::ServiceConfig) {
    cfg.route("/", web::get().to(index))
        .route("/upload", web::post().to(upload));
}

async fn index() -> impl Responder {
    HttpResponse::Ok().body("file_controller")
}

#[derive(Debug, Deserialize)]
struct UploadParam {
    id: String,
}

/// If you encounter error: `Result::unwrap()` on an `Err` value: MultipartError { source: failed to read stream }
/// Just check DefaultBodyLimit value setting in lib.rs.
async fn upload(param: web::Query<UploadParam>, mut payload: Multipart) -> impl Responder {
    // Process file upload
    while let Some(Ok(mut field)) = payload.next().await {
        let filename = field
            .content_disposition()
            .unwrap()
            .get_filename()
            .unwrap_or("tempfile");

        let filepath = format!("D:/Temp/ml/{}", filename);
        let mut f = std::fs::File::create(filepath).unwrap();

        while let Some(chunk) = field.next().await {
            let data = chunk.unwrap();
            f.write_all(&data).unwrap();
        }
    }

    println!("id value: {}", param.id);

    HttpResponse::NoContent()
}
